import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:laos_mall/app_route.dart';
import 'package:laos_mall/common/base/base_controller.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/utils/debouncer.dart';
import 'package:laos_mall/common/utils/http_util.dart';
import 'package:laos_mall/common/widght/dropdown/custom_dropdown.dart';
import 'package:laos_mall/models/category/keyword_model.dart';
import 'package:laos_mall/models/category/para_product.dart';
import 'package:laos_mall/pages/main/catergory/product_detail/view.dart';
import 'package:laos_mall/pages/main/widgets/product_item_logic.dart';

class SearchProductLogic extends BaseController {
  final searchKey = GlobalKey();
  final dropDownKey = GlobalKey<PositionedDropdownState>();
  final DeBouncer _debouncer = DeBouncer(delay: Duration(milliseconds: 1000));
  List<String> searchResult = [];
  List<Keyword_list>? keyword_list;
  ParamProduct searchPara = ParamProduct();
  var isAuto = false;
  final TextEditingController textEditingController = TextEditingController();

  void onchange(String? value) {
    if (value != null && value.isNotEmpty) {
      _debouncer.run(() {
        requestSearchValue(value);
      });
    }
  }

  search(int index) {
    searchPara.keyword = keyword_list?[index].keyword;

    textEditingController.text = searchPara.keyword ?? "";
    isAuto = true;
    final itemLogic = Get.find<ProductItemLogic>(tag: "search");
    itemLogic.requestOfService();
    Utils.closeKeyboard();
  }

  void requestSearchValue(value) async {
    var res = await HttpUtil.restApi.keywordList({"keyword": value});
    searchResult = res.data?.keyword_list.map((e) => e.keyword).toList() ?? [];
    keyword_list = res.data?.keyword_list;
    if (!isAuto) {
      print("isAuto === $isAuto");
      if (searchResult.isEmpty) return;
      dropDownKey.currentState
          ?.showDropdown(searchKey.getMaxY, items: searchResult);
    } else {
      isAuto = false;
    }
  }

  onEditingComplete() {}

  goSearch() {
    searchPara.keyword = textEditingController.text;
    final itemLogic = Get.find<ProductItemLogic>(tag: "search");
    itemLogic.requestOfService();
    dropDownKey.currentState?.hideDropdown();
    Utils.closeKeyboard();
    isAuto = true;
  }

  @override
  void dispose() {
    _debouncer.cancel();
    super.dispose();
  }
}
